package com.migu.contacts.util;

import android.text.TextUtils;

import com.frank.libandroid.GsonUtil;
import com.google.gson.reflect.TypeToken;
import com.migu.contacts.bean.AddressBean;
import com.migu.contacts.bean.ContactBean;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;

public class AddressUtil {
    private static List<AddressBean> addressBeanList = new ArrayList<>();

    static {
        String string = MMKV.defaultMMKV().getString("provinceList", "");
        if (!TextUtils.isEmpty(string)) {
            addressBeanList.addAll(GsonUtil.fromJson(string, new TypeToken<List<AddressBean>>() {
            }.getType()));
        }
    }

    public static String getName(ContactBean.Address address) {
        return getName(addressBeanList, address.provinceCode) + getName(addressBeanList, address.cityCode) + getName(addressBeanList, address.countyCode);
    }

    public static String getName(List<AddressBean> list, String code) {
        for (AddressBean addressBean : list) {
            if (addressBean.code.equals(code)) {
                return addressBean.name;
            }
        }
        return null;
    }

    public static void init(List<AddressBean> list) {
        addressBeanList.clear();
        addressBeanList.addAll(list);
        MMKV.defaultMMKV().putString("provinceList", GsonUtil.toJson(list));
    }
}
